const express = require('express');
const Activity = require('../models/Activity');
const User = require('../models/User');
const Comment = require('../models/Comment');
const ActivityRating = require('../models/ActivityRating');
const auth = require('../middleware/auth');
const { body, validationResult, query } = require('express-validator');
const { Op } = require('sequelize');
const { sequelize } = require('../config/database');

const router = express.Router();

// @route   GET /api/activities
// @desc    Get all activities with filtering and pagination
// @access  Public
router.get('/', [
  query('page').optional().isInt({ min: 1 }).withMessage('Page must be a positive integer'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be between 1 and 100'),
  query('type').optional().isIn(['music', 'sports', 'food', 'gaming', 'movie', 'travel', 'study', 'party', 'other']).withMessage('Invalid activity type'),
  query('status').optional().isIn(['draft', 'published', 'cancelled', 'ongoing', 'completed', 'expired']).withMessage('Invalid status'),
  query('lat').optional().isFloat({ min: -90, max: 90 }).withMessage('Invalid latitude'),
  query('lng').optional().isFloat({ min: -180, max: 180 }).withMessage('Invalid longitude'),
  query('radius').optional().isInt({ min: 1, max: 50000 }).withMessage('Radius must be between 1 and 50000 meters'),
  query('startDate').optional().isISO8601().withMessage('Invalid start date format'),
  query('endDate').optional().isISO8601().withMessage('Invalid end date format')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    // Build query
    const where = {};

    // Filter by type
    if (req.query.type) {
      where.type = req.query.type;
    }
    // Filter by status
    if (req.query.status) {
      where.status = req.query.status;
    } else {
      // Default to published and ongoing activities
      where.status = { [Op.in]: ['published', 'ongoing'] };
    }
    // Filter by date range
    if (req.query.startDate || req.query.endDate) {
      where.startTime = {};
      if (req.query.startDate) {
        where.startTime[Op.gte] = new Date(req.query.startDate);
      }
      if (req.query.endDate) {
        where.startTime[Op.lte] = new Date(req.query.endDate);
      }
    }

    // Execute query
    const activities = await Activity.findAll({
      where,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl', 'bio']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['status'] }  // 移除不存在的 'notes' 字段
        }
      ],
      order: [['startTime', 'ASC']],
      offset,
      limit
    });

    const total = await Activity.count({ where });
    res.json({
      success: true,
      data: {
        activities,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/nearby
// @desc    Get nearby activities based on coordinates
// @access  Public
router.get('/nearby', [
  query('latitude').optional().isFloat({ min: -90, max: 90 }).withMessage('Invalid latitude'),
  query('longitude').optional().isFloat({ min: -180, max: 180 }).withMessage('Invalid longitude'),
  query('radius').optional().isInt({ min: 100, max: 100000 }).withMessage('Radius must be between 100 and 100000 meters'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be between 1 and 100')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const latitude = parseFloat(req.query.latitude);
    const longitude = parseFloat(req.query.longitude);
    const radius = parseInt(req.query.radius, 10) || 5000;
    const limit = parseInt(req.query.limit, 10) || 20;

    if (Number.isNaN(latitude) || Number.isNaN(longitude)) {
      return res.status(400).json({
        success: false,
        message: 'Latitude and longitude are required'
      });
    }

    const activities = await Activity.findAll({
      where: {
        status: {
          [Op.in]: ['published', 'ongoing']
        }
      },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl', 'bio']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['status'] }
        }
      ]
    });

    const toRadians = (deg) => deg * (Math.PI / 180);
    const EARTH_RADIUS = 6378137; // meters

    const activitiesWithDistance = activities
      .map(activity => {
        const coords = activity.location?.coordinates;
        if (!Array.isArray(coords) || coords.length < 2) {
          return null;
        }

        const [lng, lat] = coords;
        if (typeof lat !== 'number' || typeof lng !== 'number') {
          return null;
        }

        const dLat = toRadians(lat - latitude);
        const dLng = toRadians(lng - longitude);
        const a = Math.sin(dLat / 2) ** 2 +
          Math.cos(toRadians(latitude)) * Math.cos(toRadians(lat)) *
          Math.sin(dLng / 2) ** 2;
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        const distance = EARTH_RADIUS * c;

        if (distance > radius) {
          return null;
        }

        const activityJson = activity.toJSON();
        activityJson.distance = distance;
        activityJson.distanceFormatted = distance < 1000
          ? `${Math.round(distance)}m`
          : `${(distance / 1000).toFixed(1)}km`;

        return activityJson;
      })
      .filter(Boolean)
      .sort((a, b) => a.distance - b.distance)
      .slice(0, limit);

    return res.json({
      success: true,
      data: {
        activities: activitiesWithDistance,
        pagination: {
          limit,
          total: activitiesWithDistance.length
        }
      }
    });
  } catch (error) {
    next(error);
  }
});
// @route   GET /api/activities/:id
// @desc    Get single activity by ID
// @access  Public
router.get('/:id', async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl', 'bio', 'statistics']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl', 'bio', 'gender'],
          through: { attributes: ['status', 'contactInfo', 'joinNickname', 'joinedAt'] }
        },
        {
          model: Comment,
          as: 'comments',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'nickname', 'avatarUrl']
            }
          ]
        },
        {
          model: User,
          as: 'likes',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['createdAt'] }
        },
        {
          model: ActivityRating,
          as: 'ratings',
          include: [
            {
              model: User,
              as: 'user',
              attributes: ['id', 'nickname', 'avatarUrl']
            }
          ]
        }
      ]
    });

    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if current user liked the activity (if authenticated)
    let isLikedByCurrentUser = false;
    if (req.user) {
      isLikedByCurrentUser = activity.isLikedByUser(req.user.userId);
    }

    res.json({
      success: true,
      data: {
        activity: {
          ...activity.toJSON(),
          isLikedByCurrentUser
        }
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities
// @desc    Create new activity
// @access  Private
router.post('/', auth, [
  body('title').notEmpty().withMessage('Title is required'),
  body('title').isLength({ min: 2, max: 100 }).withMessage('Title must be between 2 and 100 characters'),
  body('description').notEmpty().withMessage('Description is required'),
  body('description').isLength({ min: 10, max: 1000 }).withMessage('Description must be between 10 and 1000 characters'),
  body('type').isIn(['music', 'sports', 'food', 'gaming', 'movie', 'travel', 'study', 'party', 'other']).withMessage('Invalid activity type'),
  body('mainImage').notEmpty().withMessage('Main image is required'),
  body('startTime').isISO8601().withMessage('Invalid start time format'),
  body('endTime').isISO8601().withMessage('Invalid end time format'),
  body('maxParticipants').isInt({ min: 2, max: 1000 }).withMessage('Maximum participants must be between 2 and 1000'),
  body('location.name').notEmpty().withMessage('Location name is required'),
  body('location.address').notEmpty().withMessage('Address is required'),
  body('location.coordinates.latitude').isFloat({ min: -90, max: 90 }).withMessage('Invalid latitude'),
  body('location.coordinates.longitude').isFloat({ min: -180, max: 180 }).withMessage('Invalid longitude')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const activityData = {
      ...req.body,
      creatorId: req.user.userId,
      location: {
        ...req.body.location,
        coordinates: [
          req.body.location.coordinates.longitude,
          req.body.location.coordinates.latitude
        ]
      }
    };

    // 如果状态是 published，设置 publishedAt
    if (activityData.status === 'published') {
      activityData.publishedAt = new Date();
    }

    const activity = await Activity.create(activityData);

    // Add creator as a participant
    await activity.addParticipant(req.user.userId, { status: 'approved' }); // 使用数据库中定义的状态值

    // Update user's activity count
    const user = await User.findByPk(req.user.userId);
    if (user.statistics) {
      user.statistics.activitiesCreated = (user.statistics.activitiesCreated || 0) + 1;
      await user.save();
    }

    const populatedActivity = await Activity.findByPk(activity.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['status'] }
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: 'Activity created successfully',
      data: {
        activity: populatedActivity
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   PUT /api/activities/:id
// @desc    Update activity
// @access  Private (creator only)
router.put('/:id', auth, [
  body('title').optional().isLength({ min: 2, max: 100 }).withMessage('Title must be between 2 and 100 characters'),
  body('description').optional().isLength({ min: 10, max: 1000 }).withMessage('Description must be between 10 and 1000 characters'),
  body('type').optional().isIn(['music', 'sports', 'food', 'gaming', 'movie', 'travel', 'study', 'party', 'other']).withMessage('Invalid activity type'),
  body('startTime').optional().isISO8601().withMessage('Invalid start time format'),
  body('endTime').optional().isISO8601().withMessage('Invalid end time format'),
  body('maxParticipants').optional().isInt({ min: 2, max: 1000 }).withMessage('Maximum participants must be between 2 and 1000')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user is the creator
    if (activity.creatorId !== req.user.userId) {
      return res.status(403).json({
        success: false,
        message: 'Only the creator can update this activity'
      });
    }

    // Check if activity can be updated
    if (activity.status === 'completed') {
      return res.status(400).json({
        success: false,
        message: 'Cannot update completed activity'
      });
    }

    // Update activity
    // If location coordinates are provided, format them correctly
    if (req.body.location && req.body.location.coordinates) {
      req.body.location.coordinates = [
        req.body.location.coordinates.longitude,
        req.body.location.coordinates.latitude
      ];
    }

    // 处理状态变更的时间戳
    if (req.body.status) {
      if (req.body.status === 'published' && !activity.publishedAt) {
        req.body.publishedAt = new Date();
      } else if (req.body.status === 'cancelled' && !activity.cancelledAt) {
        req.body.cancelledAt = new Date();
      } else if (req.body.status === 'completed' && !activity.completedAt) {
        req.body.completedAt = new Date();
      }
    }

    await activity.update(req.body);

    const updatedActivity = await Activity.findByPk(activity.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['status'] }
        }
      ]
    });

    res.json({
      success: true,
      message: 'Activity updated successfully',
      data: {
        activity: updatedActivity
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   DELETE /api/activities/:id
// @desc    Delete activity
// @access  Private (creator only)
router.delete('/:id', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user is the creator
    if (activity.creatorId !== req.user.userId) {
      return res.status(403).json({
        success: false,
        message: 'Only the creator can delete this activity'
      });
    }

    // Check if activity can be deleted
    if (activity.status === 'ongoing') {
      return res.status(400).json({
        success: false,
        message: 'Cannot delete ongoing activity'
      });
    }

    // Soft delete the activity
    await activity.destroy();

    res.json({
      success: true,
      message: 'Activity deleted successfully'
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/join
// @desc    Join an activity
// @access  Private
router.post('/:id/join', auth, async (req, res, next) => {
  try {
    const { contactInfo, joinNickname } = req.body;
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // Check if activity can be joined
    if (activity.status !== 'published') {
      return res.status(400).json({
        success: false,
        message: '活动未发布，无法加入'
      });
    }

    // Check if activity is full
    if (activity.currentParticipants >= activity.maxParticipants) {
      return res.status(400).json({
        success: false,
        message: '这个活动已经满员了'
      });
    }

    // Check if user is already a participant
    const participants = await activity.getParticipants({
      where: { id: req.user.userId }
    });

    if (participants.length > 0) {
      return res.status(400).json({
        success: false,
        message: '你已经加入了这个活动'
      });
    }

    // Add user as a participant with pending status, including contact info and nickname
    // 使用query方法直接插入关联记录，确保状态为pending
    await sequelize.query(
      'INSERT INTO parkpart_activity_participants (activityId, userId, status, joinedAt, contactInfo, joinNickname, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE status = ?, contactInfo = ?, joinNickname = ?, updatedAt = ?',
      {
        replacements: [
          req.params.id, 
          req.user.userId, 
          'pending', 
          new Date(),
          contactInfo || null,
          joinNickname || null,
          new Date(), 
          new Date(),
          'pending',
          contactInfo || null,
          joinNickname || null,
          new Date()
        ]
      }
    );

    // Update participant count (only count approved participants)
    const approvedParticipants = await activity.getParticipants({
      through: { where: { status: 'approved' } }
    });
    activity.currentParticipants = approvedParticipants.length;
    await activity.save();

    res.json({
      success: true,
      message: '成功加入活动'
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/leave
// @desc    Leave an activity
// @access  Private
router.post('/:id/leave', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user is a participant
    const participants = await activity.getParticipants({
      where: { id: req.user.userId }
    });

    if (participants.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'You are not a participant of this activity'
      });
    }

    // Check if user is the creator
    if (activity.creatorId === req.user.userId) {
      return res.status(400).json({
        success: false,
        message: 'Creator cannot leave their own activity'
      });
    }

    // Check participant status before removing
    const participant = await activity.getParticipants({
      where: { id: req.user.userId },
      through: { where: { status: 'approved' } }
    });
    
    const isApprovedParticipant = participant.length > 0;
    
    // Remove user from participants
    await activity.removeParticipant(req.user.userId);

    // Update participant count only if user was an approved participant
    if (isApprovedParticipant) {
      activity.currentParticipants -= 1;
      await activity.save();
    }

    res.json({
      success: true,
      message: 'Successfully left the activity'
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/approve
// @desc    Approve a participant's request
// @access  Private (creator only)
router.post('/:id/approve', auth, async (req, res, next) => {
  try {
    const { participantId } = req.body;
    
    if (!participantId) {
      return res.status(400).json({
        success: false,
        message: '参与者ID是必需的'
      });
    }
    
    const activity = await Activity.findByPk(req.params.id);
    
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    
    // Check if user is the activity creator
    if (activity.creatorId !== req.user.userId) {
      return res.status(403).json({
        success: false,
        message: '只有活动创建者可以批准参与者'
      });
    }
    
    // Check if participant exists and has pending status
    const participant = await activity.getParticipants({
      where: { id: participantId },
      through: { where: { status: 'pending' } }
    });
    
    if (participant.length === 0) {
      return res.status(404).json({
        success: false,
        message: '找不到待审核的参与者'
      });
    }
    
    // Update participant status to approved
    await sequelize.query(
      'UPDATE parkpart_activity_participants SET status = ?, updatedAt = ? WHERE activityId = ? AND userId = ?',
      {
        replacements: ['approved', new Date(), req.params.id, participantId],
        type: sequelize.QueryTypes.UPDATE
      }
    );
    
    // Update participant count
    const approvedParticipants = await activity.getParticipants({
      through: { where: { status: 'approved' } }
    });
    activity.currentParticipants = approvedParticipants.length;
    await activity.save();
    
    res.json({
      success: true,
      message: '参与者已批准'
    });
  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/reject
// @desc    Reject a participant's request
// @access  Private (creator only)
router.post('/:id/reject', auth, async (req, res, next) => {
  try {
    const { participantId } = req.body;
    
    if (!participantId) {
      return res.status(400).json({
        success: false,
        message: '参与者ID是必需的'
      });
    }
    
    const activity = await Activity.findByPk(req.params.id);
    
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    
    // Check if user is the activity creator
    if (activity.creatorId !== req.user.userId) {
      return res.status(403).json({
        success: false,
        message: '只有活动创建者可以拒绝参与者'
      });
    }
    
    // Check if participant exists and has pending status
    const participant = await activity.getParticipants({
      where: { id: participantId },
      through: { where: { status: 'pending' } }
    });
    
    if (participant.length === 0) {
      return res.status(404).json({
        success: false,
        message: '找不到待审核的参与者'
      });
    }
    
    // Update participant status to rejected
    await sequelize.query(
      'UPDATE parkpart_activity_participants SET status = ?, updatedAt = ? WHERE activityId = ? AND userId = ?',
      {
        replacements: ['rejected', new Date(), req.params.id, participantId],
        type: sequelize.QueryTypes.UPDATE
      }
    );
    
    res.json({
      success: true,
      message: '参与者已拒绝'
    });
  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/:id/pending-participants
// @desc    Get all pending participants for an activity
// @access  Private (creator only)
router.get('/:id/pending-participants', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    
    // Check if user is the activity creator
    if (activity.creatorId !== req.user.userId) {
      return res.status(403).json({
        success: false,
        message: '只有活动创建者可以查看待审核参与者'
      });
    }
    
    // Get all pending participants with their contact info and nickname
    const pendingParticipants = await sequelize.query(
      `SELECT p.id, p.nickname, p.avatarUrl as avatar, ap.contactInfo, ap.joinNickname, ap.joinedAt
       FROM parkpart_users p
       JOIN parkpart_activity_participants ap ON p.id = ap.userId
       WHERE ap.activityId = ? AND ap.status = 'pending'`,
      {
        replacements: [req.params.id],
        type: sequelize.QueryTypes.SELECT
      }
    );
    
    res.json({
      success: true,
      data: {
        pendingParticipants
      }
    });
  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/:id/user-status
// @desc    Get current user's status for an activity (like, participation, etc.)
// @access  Private
router.get('/:id/user-status', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'likes',
          attributes: ['id'],
          through: { attributes: [] }
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id'],
          through: { attributes: ['status', 'joinedAt'] }
        }
      ]
    });

    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user liked the activity
    const isLiked = activity.isLikedByUser(req.user.userId);

    // Check if user is a participant
    const isParticipant = activity.isUserParticipant(req.user.userId);

    // Get participant status if user is a participant
    let participantStatus = null;
    let joinedAt = null;
    if (isParticipant) {
      const participant = activity.participants.find(p => p.id === req.user.userId);
      if (participant) {
        participantStatus = participant.parkpart_activity_participants ?
          participant.parkpart_activity_participants.status : 'approved';
        joinedAt = participant.parkpart_activity_participants ?
          participant.parkpart_activity_participants.joinedAt : null;
      }
    }

    // Check if user is the creator
    const isCreator = activity.isCreator(req.user.userId);

    // 检查用户是否可以重新申请加入活动
    let canReapply = false;
    if (isParticipant && (participantStatus === 'rejected' || participantStatus === 'cancelled')) {
      canReapply = activity.canJoin(req.user.userId);
    }

    // 使用异步方法检查用户是否可以离开活动
    const canLeave = await activity.canLeave(req.user.userId);

    res.json({
      success: true,
      data: {
        activityId: activity.id,
        userId: req.user.userId,
        isLiked,
        isParticipant,
        participantStatus,
        joinedAt,
        isCreator,
        canJoin: activity.canJoin(req.user.userId),
        canLeave, // 使用异步方法的结果
        canReapply,
        canLike: !isCreator,
        canUnlike: isLiked,
        isActivityFull: activity.isFull(),
        isActivityOngoing: activity.isOngoing(),
        isActivityUpcoming: activity.isUpcoming()
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/like
// @desc    Like an activity
// @access  Private
router.post('/:id/like', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'likes',
          attributes: ['id'],
          through: { attributes: [] }
        }
      ]
    });

    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }
    //暂时取消
    // // Check if user is the creator
    // if (activity.creatorId === req.user.userId) {
    //   return res.status(400).json({
    //     success: false,
    //     message: '参与者不能点赞自己的活动'
    //   });
    // }

    // // Check if user already liked the activity
    // if (activity.isLikedByUser(req.user.userId)) {
    //   return res.status(400).json({
    //     success: false,
    //     message: '参与者已点赞此活动'
    //   });
    // }

    // Add user like
    await activity.addLike(req.user.userId);

    // Update creator's statistics
    const creator = await User.findByPk(activity.creatorId);
    if (creator && creator.statistics) {
      creator.statistics.totalLikesReceived = (creator.statistics.totalLikesReceived || 0) + 1;
      await creator.save();
    }

    // Get updated activity with like count
    const updatedActivity = await Activity.findByPk(activity.id, {
      include: [
        {
          model: User,
          as: 'likes',
          attributes: ['id'],
          through: { attributes: [] }
        }
      ]
    });

    res.json({
      success: true,
      message: 'Activity liked successfully',
      data: {
        activityId: activity.id,
        userId: req.user.userId,
        isLiked: true,
        likeCount: updatedActivity.likes.length
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   DELETE /api/activities/:id/like
// @desc    Unlike an activity
// @access  Private
router.delete('/:id/like', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'likes',
          attributes: ['id'],
          through: { attributes: [] }
        }
      ]
    });

    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user has not liked the activity
    if (!activity.isLikedByUser(req.user.userId)) {
      return res.status(400).json({
        success: false,
        message: 'You have not liked this activity'
      });
    }

    // Remove user like
    await activity.removeLike(req.user.userId);

    // Update creator's statistics
    const creator = await User.findByPk(activity.creatorId);
    if (creator && creator.statistics && creator.statistics.totalLikesReceived > 0) {
      creator.statistics.totalLikesReceived = creator.statistics.totalLikesReceived - 1;
      await creator.save();
    }

    // Get updated activity with like count
    const updatedActivity = await Activity.findByPk(activity.id, {
      include: [
        {
          model: User,
          as: 'likes',
          attributes: ['id'],
          through: { attributes: [] }
        }
      ]
    });

    res.json({
      success: true,
      message: 'Activity unliked successfully',
      data: {
        activityId: activity.id,
        userId: req.user.userId,
        isLiked: false,
        likeCount: updatedActivity.likes.length
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/comments
// @desc    Add comment to activity
// @access  Private
router.post('/:id/comments', auth, [
  body('content').notEmpty().withMessage('Comment content is required'),
  body('content').isLength({ min: 1, max: 500 }).withMessage('Comment must be between 1 and 500 characters')
], async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Create comment using Comment model
    const comment = await Comment.create({
      activityId: req.params.id,
      userId: req.user.userId,
      content: req.body.content,
      images: req.body.images || []
    });

    // Fetch the comment with author information
    const newComment = await Comment.findByPk(comment.id, {
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'nickname', 'avatarUrl']
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: 'Comment added successfully',
      data: {
        comment: newComment
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   DELETE /api/activities/:id/comments/:commentId
// @desc    Delete comment from activity
// @access  Private (comment owner or activity creator)
router.delete('/:id/comments/:commentId', auth, async (req, res, next) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Find the comment using Comment model
    const comment = await Comment.findOne({
      where: {
        id: req.params.commentId,
        activityId: req.params.id
      }
    });

    if (!comment) {
      return res.status(404).json({
        success: false,
        message: 'Comment not found'
      });
    }

    // Check if user is the comment owner or activity creator
    const isCommentOwner = comment.userId === req.user.userId;
    const isActivityCreator = activity.creatorId === req.user.userId;

    if (!isCommentOwner && !isActivityCreator) {
      return res.status(403).json({
        success: false,
        message: 'You can only delete your own comments or comments on your activities'
      });
    }

    // Soft delete the comment
    await comment.destroy();

    res.json({
      success: true,
      message: 'Comment deleted successfully'
    });

  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/:id/comments
// @desc    获取活动的评论列表
// @access  Public
router.get('/:id/comments', [
  query('page').optional().isInt({ min: 1 }).withMessage('页码必须是大于0的整数'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间')
], async (req, res, next) => {
  try {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '参数验证失败',
        errors: errors.array()
      });
    }

    // 获取分页参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    // 检查活动是否存在
    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // 查询评论总数
    const total = await Comment.count({
      where: {
        activityId: req.params.id
      }
    });

    // 查询评论列表
    const comments = await Comment.findAll({
      where: {
        activityId: req.params.id
      },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'nickname', 'avatarUrl']
        }
      ],
      order: [['createdAt', 'DESC']], // 按创建时间倒序排列
      offset,
      limit
    });

    // 返回评论列表和分页信息
    res.json({
      success: true,
      message: '获取评论列表成功',
      data: {
        comments,
        pagination: {
          page,          // 当前页码
          limit,         // 每页数量
          total,         // 总评论数
          pages: Math.ceil(total / limit)  // 总页数
        }
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/user/:userId
// @desc    Get activities created by a specific user
// @access  Public
router.get('/user/:userId', [
  query('page').optional().isInt({ min: 1 }).withMessage('Page must be a positive integer'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be between 1 and 100')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const activities = await Activity.findAll({
      where: {
        creatorId: req.params.userId,
        status: { [Op.in]: ['published', 'ongoing', 'completed'] }
      },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: { attributes: ['status'] }
        }
      ],
      order: [['createdAt', 'DESC']],
      offset,
      limit
    });

    const total = await Activity.count({
      where: {
        creatorId: req.params.userId,
        status: { [Op.in]: ['published', 'ongoing', 'completed'] }
      }
    });

    res.json({
      success: true,
      data: {
        activities,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   GET /api/activities/user/:userId/participating
// @desc    Get activities a user is participating in
// @access  Public
router.get('/user/:userId/participating', [
  query('page').optional().isInt({ min: 1 }).withMessage('Page must be a positive integer'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be between 1 and 100'),
  query('status').optional().isIn(['pending', 'approved', 'rejected', 'cancelled']).withMessage('Invalid participation status')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    // Build query for participation status
    const participantWhere = {};
    if (req.query.status) {
      participantWhere.status = req.query.status;
    }

    const activities = await Activity.findAll({
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'nickname', 'avatarUrl']
        },
        {
          model: User,
          as: 'participants',
          attributes: ['id', 'nickname', 'avatarUrl'],
          through: {
            attributes: ['status'],  // 移除不存在的 'notes' 字段
            where: participantWhere
          },
          where: {
            id: req.params.userId
          }
        }
      ],
      where: {
        status: { [Op.in]: ['published', 'ongoing', 'completed'] }
      },
      order: [['startTime', 'ASC']],
      offset,
      limit
    });

    // Get total count for pagination
    const totalCount = await Activity.count({
      include: [
        {
          model: User,
          as: 'participants',
          attributes: [],
          through: {
            where: participantWhere
          },
          where: {
            id: req.params.userId
          }
        }
      ],
      where: {
        status: { [Op.in]: ['published', 'ongoing', 'completed'] }
      }
    });

    res.json({
      success: true,
      data: {
        activities,
        pagination: {
          page,
          limit,
          total: totalCount,
          pages: Math.ceil(totalCount / limit)
        }
      }
    });

  } catch (error) {
    next(error);
  }
});

// @route   POST /api/activities/:id/rate
// @desc    Rate an activity
// @access  Private
router.post('/:id/rate', auth, [
  body('rating').isInt({ min: 1, max: 5 }).withMessage('Rating must be between 1 and 5'),
  body('comment').optional().isLength({ max: 500 }).withMessage('Comment must be less than 500 characters')
], async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: 'Validation failed',
        errors: errors.array()
      });
    }

    const activity = await Activity.findByPk(req.params.id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: 'Activity not found'
      });
    }

    // Check if user has participated in the activity
    const participants = await activity.getParticipants({
      where: { id: req.user.userId }
    });

    if (participants.length === 0) {
      return res.status(403).json({
        success: false,
        message: 'You can only rate activities you have participated in'
      });
    }

    // Check if activity is completed
    if (activity.status !== 'completed') {
      return res.status(400).json({
        success: false,
        message: 'You can only rate completed activities'
      });
    }

    // Check if user has already rated this activity
    const existingRating = await ActivityRating.findOne({
      where: {
        activityId: req.params.id,
        userId: req.user.userId
      }
    });

    if (existingRating) {
      // Update existing rating
      await existingRating.update({
        rating: req.body.rating,
        comment: req.body.comment || null
      });
    } else {
      // Create new rating
      await ActivityRating.create({
        activityId: req.params.id,
        userId: req.user.userId,
        rating: req.body.rating,
        comment: req.body.comment || null
      });
    }

    // Calculate new average rating
    const ratings = await ActivityRating.findAll({
      where: { activityId: req.params.id }
    });

    const totalRating = ratings.reduce((sum, rating) => sum + rating.rating, 0);
    const averageRating = totalRating / ratings.length;

    // Update activity's average rating
    await activity.update({ averageRating });

    res.json({
      success: true,
      message: 'Activity rated successfully',
      data: {
        averageRating
      }
    });

  } catch (error) {
    next(error);
  }
});

module.exports = router;
